<?php
/**
 * Created by PhpStorm.
 * User: Young<YoungShen@fih-foxconn.com.cn
 * Date: 2019/3/14
 * Time: 8:12
 */

namespace App\Services;

use EasyWeChat;
use mysql_xdevapi\Exception;
use Cache;

class WxAppService
{
    protected $appid = "wxd46e7c95a833a0b1";
    protected $appSecret = "efed99d5b0c373513d622cb55ade5aa9";
    protected $mini_program;

/*    public function __construct()
    {

        $this->mini_program =EasyWeChat::officialAccount();
    }*/

    public function qrCode($scene,$pagePath,$width=430){
        $response = $this->mini_program ->app_code->getUnlimit($scene, [
            'page'  => $pagePath,
            'width' => $width,
        ]);
        // $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例，失败为数组或你指定的 API 返回类型
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            return $response;
        }else{
            throw new Exception('生成失败',10002);
        }

    }

    //获取access_token
      public function get_access_token(){
        $token = Cache::has('access_token');
        if(empty($token)){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appSecret}";
            $res = json_decode(Request_url($url));
            if(empty($res->access_token)){
                return false;
            }else{
                Cache::add('access_token',$res->access_token,($res->expires_in - 60)/60);
                return $res->access_token;
            }
        }else{
            return $token;
        }
    }
}
